
package com.zcp.pcsuitall;

import com.zcp.pcsuitall.business.AppManager;
import com.zcp.pcsuitall.business.CalendarManager;
import com.zcp.pcsuitall.business.CallLogManager;
import com.zcp.pcsuitall.business.ContactsManager;
import com.zcp.pcsuitall.business.FileManager;
import com.zcp.pcsuitall.business.MusicManager;
import com.zcp.pcsuitall.business.PictureManager;
import com.zcp.pcsuitall.business.SmsInfoManager;
import com.zcp.pcsuitall.business.SystemInfoManager;
import com.zcp.pcsuitall.business.VideoManager;

import android.content.Context;
import android.util.Log;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * 主要是用来控制业务分发。
 */
public class BusinessControl {

//    private static String policy="<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"1025-9999\"/></cross-domain-policy>\\0";
    /**
     * 处理业务，如果是关闭那么就关闭，否则就转到处理相关的业务。
     * 
     * @param key
     */
    public static void dealWithBusiness(SelectionKey key, Context context, String cipherKey) {
        SocketChannel sc = null;
        try {

            sc = (SocketChannel) key.channel();
            String source = XmlDataDealWith.getDataFromChannel(sc, cipherKey);
            
//            if("<policy-file-request/>".equals(source))
//            {
//                returnToClient(sc,policy
//                       , context);
//                return;
//            }
          
            
            Action action = getAction(source);
            if (FORMATERROR.equals(action.getName())) {
                BusinessControl.returnToClient(
                        sc,
                        XmlDataDealWith.getErrorString(FORMATERROR, "2",
                                context.getString(R.string.cmdFormatError_2)), context);
                return;
            }
            // 检查命令中是否有action和输入格式是否合法
            if (!checkFormatIsOk(sc, action, context)) {
                return;
            }
            // 检查是否是关闭通道命令
            if ((action.getName().equalsIgnoreCase(Constant.CLOSE_CHANNEL))) {
                closeSocketChannel(key, context);
                Log.e(TAG, "BusinessControl  close channel by client");
                return;
            }
            // 检查是否是重置密钥
            if ((action.getName().equalsIgnoreCase("ResetKey"))) {
                dealWithRetSetKey(sc, context, cipherKey);
                Log.e(TAG, "BusinessControl  ResetKey channel by client");
                return;
            }
            IDealWithMessage message = getMessage(action.getName());
            // 判断action中命令是否是接口中定义存在的
            if (message == null) {
                returnToClient(
                        sc,
                        XmlDataDealWith.getErrorString(action.getName(), "5",
                                context.getString(R.string.notSupportCmd_5)), context);
                return;
            }
            // 如果上述检查都没有问题那么就处理相关数据
            message.dealWith(sc, action, context);

        } catch (Exception e) {
            Log.e(TAG, "dealWithBusiness  error");
            e.printStackTrace();
            returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString("dealWithBusiness", e.toString()), context);
        }
    }

    private static Action getAction(String source) {
        return XmlDataDealWith.getActionValue(source);
    }

    /**
     * 检查命令的输入参数格式是否符合xml语法。
     * 
     * @param sc
     * @param action
     * @param context
     * @return
     */
    private static boolean checkFormatIsOk(SocketChannel sc, Action action, Context context) {

        // 判断anction中是否有命令数据。
        if (action.getName() == null || action.getName().trim().equals("")) {
            returnToClient(
                    sc,
                    XmlDataDealWith.getErrorString("null", "1",
                            context.getString(R.string.notActionError_1)), context);
            return false;
        }
        return true;
    }

    /**
     * 关闭通道。
     * 
     * @param sc
     */
    public static void closeSocketChannel(SelectionKey key, Context context) {
        if (key != null) {

            try {
                if (context instanceof SocketService) {
                    SocketService service = (SocketService) context;
                    service.closeSocketChannel(key);
                }
            } catch (Exception e) {
                Log.e(TAG, "close error" + e.getMessage());
            }
        }
    }

    /**
     * 返回数据到客户端。
     * 
     * @param sc
     * @param data 字符串形式数据。
     */
    public static void returnToClient(SocketChannel sc, String data, Context context) {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;
            service.sendData(sc, data);
        }
    }

    public static void dealWithRetSetKey(SocketChannel sc, Context context, String cipherKey) {
        if (context != null && (context instanceof SocketService)) {
            SocketService service = (SocketService) context;

            String returnStr = service.resetCipherKey();
            StringBuilder returnMessageV = new StringBuilder();
            returnMessageV.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            returnMessageV.append("<root><action>ResetKey</action><data>");
            returnMessageV.append("<key>" + returnStr + "</key>");
            returnMessageV.append("</data></root>");

            service.sendData(sc, returnMessageV.toString(), cipherKey);
        }
    }

    private static IDealWithMessage getMessage(String key) {

        IDealWithMessage message = null;
        String objectKey = null;
        boolean shouldAdd = false;
        if (APP_MANAGER.contains(key)) {
            objectKey = "APP_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new AppManager();
                shouldAdd = true;
            }
        } else if (SYS_MANAGER.contains(key)) {
            objectKey = "SYS_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new SystemInfoManager();
                shouldAdd = true;
            }
        } else if (SMS_MANAGER.contains(key)) {
            objectKey = "SMS_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new SmsInfoManager();
                shouldAdd = true;
            }
        } else if (CONTACT_MANAGER.contains(key)) {
            objectKey = "CONTACT_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new ContactsManager();
                shouldAdd = true;
            }
        } else if (CALLLOG_MANAGER.contains(key)) {
            objectKey = "CALLLOG_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new CallLogManager();
                shouldAdd = true;
            }
        } else if (FILE_MANAGER.contains(key)) {
            objectKey = "FILE_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new FileManager();
                shouldAdd = true;
            }

        } else if (PIC_MANAGER.contains(key)) {
            objectKey = "PIC_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new PictureManager();
                shouldAdd = true;
            }
        } else if (VIDEO_MANAGER.contains(key)) {
            objectKey = "VIDEO_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new VideoManager();
                shouldAdd = true;
            }
        } else if (MUSIC_MANAGER.contains(key)) {
            objectKey = "MUSIC_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new MusicManager();
                shouldAdd = true;
            }
        }else if (CALENDAR_MANAGER.contains(key)) {
            objectKey = "CALENDAR_MANAGER";
            message = catchMessageDealWith.get(objectKey);
            if (message == null) {
                message = new CalendarManager();
                shouldAdd = true;
            }
        }
        if (shouldAdd && message != null && objectKey != null) {
            catchMessageDealWith.put(objectKey, message);
            Log.i("222", "new object " + objectKey);
        }
        return message;
    }

    private static HashMap<String, IDealWithMessage> catchMessageDealWith = new HashMap<String, IDealWithMessage>();

    private static String TAG = "BusinessControl";

    private static final String FORMATERROR = "formatError";

    private static LinkedList<String> APP_MANAGER = new LinkedList<String>();

    private static LinkedList<String> SYS_MANAGER = new LinkedList<String>();

    private static LinkedList<String> SMS_MANAGER = new LinkedList<String>();

    private static LinkedList<String> CONTACT_MANAGER = new LinkedList<String>();

    private static LinkedList<String> CALLLOG_MANAGER = new LinkedList<String>();

    private static LinkedList<String> FILE_MANAGER = new LinkedList<String>();

    private static LinkedList<String> PIC_MANAGER = new LinkedList<String>();

    private static LinkedList<String> MUSIC_MANAGER = new LinkedList<String>();

    private static LinkedList<String> VIDEO_MANAGER = new LinkedList<String>();
    
    private static LinkedList<String> CALENDAR_MANAGER = new LinkedList<String>();
    static {
        // 加载应用程序支持的服务
        APP_MANAGER.add("LoadApplication");
        APP_MANAGER.add("ReadApplicationInfo");
        APP_MANAGER.add("InstallApp");
        APP_MANAGER.add("UnInstallApp");

        // 加载系统信息支持的服务
        SYS_MANAGER.add("LoadSystemInfo");
        SYS_MANAGER.add("LoadStateInfo");
        SYS_MANAGER.add("CheckKey");

        // 加载短信支持的服务
        SMS_MANAGER.add("LoadSMS");
        SMS_MANAGER.add("AddSMS");
        SMS_MANAGER.add("CleanupSMS");
        SMS_MANAGER.add("DeleteSMS");
        SMS_MANAGER.add("ReadSMSCapacity");
        SMS_MANAGER.add("ReadSMSTotal");
        SMS_MANAGER.add("SendSMS");
        // 加载联系人支持的服务
        CONTACT_MANAGER.add("LoadContact");
        CONTACT_MANAGER.add("ReadContactCapacity");
        CONTACT_MANAGER.add("AddContact");
        CONTACT_MANAGER.add("ModifyContact");
        CONTACT_MANAGER.add("DeleteContact");
        CONTACT_MANAGER.add("CleanupContact");
        CONTACT_MANAGER.add("ReadContactTotal");
        CONTACT_MANAGER.add("LoadContactGroup");
        CONTACT_MANAGER.add("AddContactGroup");
        CONTACT_MANAGER.add("ModifyContactGroup");
        CONTACT_MANAGER.add("DeleteContactGroup");
        
        //加载通话记录
        CALLLOG_MANAGER.add("LoadCallLog");
        CALLLOG_MANAGER.add("AddCalllog");
        CALLLOG_MANAGER.add("CleanupCalllog");
        CALLLOG_MANAGER.add("DeleteCalllog");

        FILE_MANAGER.add("LoadFile");
        FILE_MANAGER.add("GetSdcardFileName");
        FILE_MANAGER.add("StartDataPort");
        FILE_MANAGER.add("SaveFile");
        FILE_MANAGER.add("CheckLoadFile");
        FILE_MANAGER.add("StopDataPort");
        FILE_MANAGER.add("cancelFileTran");
        

        PIC_MANAGER.add("GetPicInfo");
        PIC_MANAGER.add("DeletePic");
        PIC_MANAGER.add("GetThumbnail");

        // 加载音乐的服务
        MUSIC_MANAGER.add("GetMusicInfo");
        MUSIC_MANAGER.add("DeleteMusic");

        // 视频服务
        VIDEO_MANAGER.add("GetVideoInfo");
        VIDEO_MANAGER.add("DeleteVideo");
        VIDEO_MANAGER.add("DeleteVideo");
        
        // 日历服务
        CALENDAR_MANAGER.add("LoadCalendar");
        CALENDAR_MANAGER.add("AddCalendar");
        CALENDAR_MANAGER.add("ModifyCalendar");
        CALENDAR_MANAGER.add("DeleteCalendar");

    };

}
